package cn.com.doone.common.uc.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CryptTools {
	
	// public static final String KEY = "fdas67^&23fDreE2&YHE2d%#"; // 加密密钥
	
	/**
	 * 3DESECB加密,key必须是长度大于等于 3*8 = 24 位  
	 * 
	 * @param src
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptThreeDESECB(String src,String key) throws Exception
	{
	    DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
	    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
	    SecretKey securekey = keyFactory.generateSecret(dks);
	    
	    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
	    cipher.init(Cipher.ENCRYPT_MODE, securekey);
	    byte[] b=cipher.doFinal(src.getBytes());
	    
	    BASE64Encoder encoder = new BASE64Encoder();
	    
	    System.out.println(b);
	    
	    return encoder.encode(b).replaceAll("\r", "").replaceAll("\n", "");
	    
	}
	
	public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws Exception {  
        DESedeKeySpec spec = new DESedeKeySpec(key);  
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");  
        SecretKey sec = keyFactory.generateSecret(spec);  
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");  
        IvParameterSpec IvParameters = new IvParameterSpec(iv);  
        cipher.init(Cipher.ENCRYPT_MODE, sec, IvParameters);  
        return cipher.doFinal(data);  
    }

	
	
	/**
	 * 3DESECB解密,key必须是长度大于等于 3*8 = 24 位  
	 * 
	 * @param src
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptThreeDESECB(String src,String key) throws Exception  
	{  
	    //--通过base64,将字符串转成byte数组  
	    BASE64Decoder decoder = new BASE64Decoder();  
	    byte[] bytesrc = decoder.decodeBuffer(src);  
	    //--解密的key  
	    DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));  
	    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");  
	    SecretKey securekey = keyFactory.generateSecret(dks);  
	      
	    //--Chipher对象解密  
	    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");  
	    cipher.init(Cipher.DECRYPT_MODE, securekey);  
	    byte[] retByte = cipher.doFinal(bytesrc);  
	      
	    return new String(retByte);  
	}  
}
